package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.utils.FastDFSClient;
import com.changgou.file.utils.FastDFSFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.cert.Extension;

@RestController
@CrossOrigin
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile multipartFile){
        try {
            String fileName = multipartFile.getOriginalFilename();//获取文件原始名
            String ext = fileName.substring(fileName.lastIndexOf("."));//获取文件扩展名
            byte[] content = multipartFile.getBytes();//获取文件内容
            //上传文件
            FastDFSFile fastDFSFile = new FastDFSFile(fileName, content, ext);
            String[] upload = FastDFSClient.upload(fastDFSFile);

            if (upload!=null&&upload.length==2){
                String url = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];
                return new Result(true, StatusCode.OK, "上传成功", url);
            }else {
                return new Result(false, StatusCode.ERROR, "上传失败");
            }


        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "上传失败");
        }


    }

}
